<?php


namespace App\Http\Controllers\Admin\Connect;


use App\Enums\GiftOpTypeEnum;
use App\Enums\GiftCategoryIdEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
//人脉礼物
class GiftController extends BaseController
{
    /**
     * @api {post} /connect/gift 人脉礼物新增
     *
     * @apiGroup 人脉-信物
     *
     * @apiParam {String} gift_name 礼物名称，必须
     * @apiParam {Int} gift_price 礼物价格，必须
     * @apiParam {String} picture 图片，必须
     * @apiParam {String} special 特效，必须
     * @apiParam {Int} sale_status 出售状态：1：上架；0：下架；必须
     * @apiParam {String} gift_desc 礼物说明
     * @apiParam {Int} prize_pool_id 奖池id，无关联奖池则传0，必须
     * @apiParam {Int} relation_type 关系类别，必须
     * @apiParam {String} relation_name 关系名称，必须
     * @apiParam {Int} connect_level 人脉等级，目前仅1/2/3，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function add(Request $request)
    {
        $relationOpType = GiftOpTypeEnum::CP . ',' . GiftOpTypeEnum::STUDENT . ',' . GiftOpTypeEnum::FRIEND;
        $param = $request->only('gift_name', 'gift_price', 'picture', 'special', 'sale_status', 'gift_desc', 'prize_pool_id', 'relation_type', 'relation_name', 'connect_level');
        $v = app('validator')->make($param, [
            'gift_name' => 'required|string|max:16',
            'gift_price' => 'required|integer|min:1',
            'picture' => 'required|url|max:255',
            'special' => "required_if:relation_type,{$relationOpType}|url|max:255",
            'sale_status' => 'required|integer|in:1,0',
            'gift_desc' => 'string|max:30',
            'prize_pool_id' => "required_if:relation_type,{$relationOpType}|integer|min:0",
            'relation_type' => 'required|integer|in:' . implode(',', array_column(GiftOpTypeEnum::CONNECT, 'id')),
            'relation_name' => "required_if:relation_type,{$relationOpType}|string|max:10",
            'connect_level' => "required_if:relation_type,{$relationOpType}|integer|in:1,2,3",
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $param['module'] = 2;
        $param['op_type'] = $param['relation_type'];
        $param['category_id'] = GiftCategoryIdEnum::CONNECT;

        $res = app('repo_gift')->addOrEdit($param);
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '添加失败');
    }

    /**
     * @api {get} /connect/gift/detail 获取人脉礼物详情
     *
     * @apiGroup 人脉-信物
     *
     * @apiParam {Int} id 礼物id，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "id": 550, 序号
    "name": "康乃馨", 礼物名称
    "category_id": 1, 分类id
    "type": 26,
    "ext_field": {
    "relation_name": "良师益友", 关系名称
    "connect_level": 1 人脉关系等级
    },
    "price": 100, 价格
    "picture": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/61becc96de83d4e3c900a3eaf825d5c7ESaEa.png", 图片url
    "special": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/78a541ee5c13663ab7e89d0bb321a2beQX4uB.mp4", 特效url
    "desc": "", 礼物说明
    "sold": 1, 销售状态：1：上架；0：下架
    "op_type": 22, 关系类别
    "prize_pool_group_id": 0 关联的奖池id
    }
    }
     */
    public function detail(Request $request)
    {
        $param = $request->only('id');
        $v = app('validator')->make($param, [
            'id' => 'required|integer',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $detail = app('model_gift')
            ->select('id', 'name', 'type', 'price', 'picture', 'special', 'desc', 'sold', 'op_type', 'prize_pool_group_id')
            ->where('id', $param['id']) //人脉相关礼物
            ->first();
        $detail->ext_field = app('model_gift_extend')
            ->select('relation_name', 'connect_level')
            ->where('gift_id', $param['id'])->first();

        if ($detail->sold == 2) $detail->sold = 0;
        return Response::sendData($detail);
    }

    /**
     * @api {put} /connect/gift 人脉礼物编辑
     *
     * @apiGroup 人脉-信物
     *
     * @apiParam {Int} id 礼物id，必须
     * @apiParam {String} gift_name 礼物名称，必须
     * @apiParam {Int} gift_price 礼物价格，必须
     * @apiParam {String} picture 图片，必须
     * @apiParam {String} special 特效，必须
     * @apiParam {Int} sale_status 出售状态：1：上架；0：下架；必须
     * @apiParam {String} gift_desc 礼物说明
     * @apiParam {Int} prize_pool_id 奖池id，无关联奖池则传0，必须
     * @apiParam {Int} relation_type 关系类别，必须
     * @apiParam {String} relation_name 关系名称，必须
     * @apiParam {Int} connect_level 人脉等级，目前仅1/2/3，必须
     * @apiParam {Int} prize_pool_id 奖池id，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function edit(Request $request)
    {
        $relationOpType = GiftOpTypeEnum::CP . ',' . GiftOpTypeEnum::STUDENT . ',' . GiftOpTypeEnum::FRIEND;
        $param = $request->only('id', 'gift_name', 'gift_price', 'picture', 'special', 'sale_status', 'gift_desc', 'prize_pool_id', 'relation_type', 'relation_name', 'connect_level');
        $v = app('validator')->make($param, [
            'id' => 'required|integer',
            'gift_name' => 'required|string|max:16',
            'gift_price' => 'required|integer|min:1',
            'picture' => 'required|url|max:255',
            'special' => "required_if:relation_type,{$relationOpType}|url|max:255",
            'sale_status' => 'required|integer|in:1,0',
            'gift_desc' => 'string|max:30',
            'prize_pool_id' => "required_if:relation_type,{$relationOpType}|integer|min:0",
            'relation_type' => 'required|integer|in:' . implode(',', array_column(GiftOpTypeEnum::CONNECT, 'id')),
            'relation_name' => "required_if:relation_type,{$relationOpType}|string|max:10",
            'connect_level' => "required_if:relation_type,{$relationOpType}|integer|in:1,2,3",
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $param['module'] = 2;
        $param['op_type'] = $param['relation_type'];
        $param['category_id'] = GiftCategoryIdEnum::CONNECT;

        $res = app('repo_gift')->addOrEdit($param);
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '编辑失败');
    }

    /**
     * @api {get} /connect/gift 人脉礼物列表
     *
     * @apiGroup 人脉-信物
     *
     * @apiParam {Int} relation_type 关系类别，0：不限制（默认）；其它根据获取人脉关系类型接口
     * @apiParam {String} gift_name 礼物名称
     * @apiParam {Int} gift_price 礼物价格
     * @apiParam {Int} sale_status 出售状态：-1：不限制（默认）；1：上架；0：下架
     * @apiParam {String} add_time 添加时间，yyyy-mm-dd
     * @apiParam {Int} page 第几页，默认1
     * @apiParam {Int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 544, 序号
    "name": "狗尾巴草", 礼物名称
    "type": 2,
    "price": 2222, 礼物价格
    "picture": "http://picture.jpg", 图片
    "special": "http://special.jpg", 特效
    "sold": 1, 销售状态：1：上架；2：下架
    "created_at": "2021-08-06 16:45:24", 添加时间
    "relation_type_name": "密友", 关系类别名称
    "relation_name": "青梅竹马", 关系名称
    "prize_pool_name": "" 奖池名称
    }
    ],
    "first_page_url": "http://local.qipaoadmin/gift/connect?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/gift/connect?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/gift/connect",
    "per_page": 10,
    "prev_page_url": null,
    "to": 1,
    "total": 1
    }
    }
     */
    public function list(Request $request)
    {
        $param = $request->only('relation_type', 'gift_name', 'gift_price', 'sale_status', 'add_time', 'page', 'page_size');
        $v = app('validator')->make($param, [
            'relation_type' => 'integer',
            'gift_name' => 'string|max:15',
            'gift_price' => 'integer|min:1',
            'sale_status' => 'integer|in:1,0',
            'add_time' => 'date_format:Y-m-d',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $relationType = $param['relation_type'] ?? 0;
        $giftName = $param['gift_name'] ?? '';
        $giftPrice = $param['gift_price'] ?? 0;
        $saleStatus = $param['sale_status'] ?? -1;
        $addTime = $param['add_time'] ?? '';
        $pageSize = $param['page_size'] ?? 10;

        $where = [];
        if ($relationType > 0) {
            $where[] = ['op_type', '=', $relationType];
        }
        if ($giftName) {
            $where[] = ['name', 'like', "%$giftName%"];
        }
        if ($giftPrice > 0) {
            $where[] = ['price', '=', $giftPrice];
        }
        if ($saleStatus === '0') {
            $where[] = ['sold', '=', 2];
        } else if ($saleStatus === '1') {
            $where[] = ['sold', '=', 1];
        }
        if ($addTime) {
            $where[] = ['created_at', '>=', $addTime . ' 0:0:0'];
            $where[] = ['created_at', '<=', $addTime . ' 23:59:59'];
        }

        $list = app('model_gift')
            ->select('id', 'name', 'type', 'price', 'picture', 'special', 'sold', 'op_type', 'prize_pool_group_id', 'created_at')
            ->where('module', 2) //人脉相关礼物
            ->where('is_delete', 0)
            ->whereIn('op_type', array_keys(GiftOpTypeEnum::CONNECT))
            ->where($where)
            ->orderBy('id', 'desc')->paginate($pageSize);
        foreach ($list as &$v) {
            //关系类别名称
            $v->relation_type_name = GiftOpTypeEnum::CONNECT[$v->op_type]['name'];
            //扩展字段
            $extField = app('model_gift_extend')
                ->select('relation_name', 'connect_level')
                ->where('gift_id', $v->id)->first();;
            //关系名称
            if ($extField) {
                $v->relation_name = $extField->relation_name;
                $v->connect_level = $extField->connect_level;
            } else {
                $v->relation_name = '';
                $v->connect_level = '';
            }

            //奖池名称
            if ($v->prize_pool_group_id > 0) {
                $v->prize_pool_name = app('model_connect_prize_pool')
                    ->where('id', $v->prize_pool_group_id)->value('name');
            } else $v->prize_pool_name = '';
        }

        return Response::sendData($list);
    }

    /**
     * @api {get} /connect/gift/give-record 亲密礼物赠送记录
     *
     * @apiGroup 人脉-信物
     *
     * @apiParam {Int} give_user_code 送礼用户code
     * @apiParam {String} give_user_nickname 送礼用户昵称
     * @apiParam {String} start_time 开始时间，yyyy-mm-dd
     * @apiParam {String} end_time 结束时间，yyyy-mm-dd
     * @apiParam {Int} page 第几页，默认1
     * @apiParam {Int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 341, 序号
    "user_id": 1309883,
    "to_user_id": 643816,
    "gift_id": 545,
    "gift_op_type": 0,
    "winner_res": "{\"type\":1,\"num\":1,\"id\":87}",
    "created_at": "2021-08-11 10:46:40", 赠送时间
    "give_user_code": 6439782, 送礼用户code
    "give_user_nickname": "坡良工6439782", 送礼用户昵称
    "receive_user_code": 7875929, 收礼用户code
    "receive_user_nickname": "亍念烟", 收礼用户昵称
    "gift_name": "桔梗之恋", 亲密礼物名称
    "winner_gift_name": "情书" 中奖道具名称
    }
    ],
    "first_page_url": "http://local.qipaoadmin/connect/gift/give-record?page=1",
    "from": 1,
    "last_page": 24,
    "last_page_url": "http://local.qipaoadmin/connect/gift/give-record?page=24",
    "next_page_url": "http://local.qipaoadmin/connect/gift/give-record?page=2",
    "path": "http://local.qipaoadmin/connect/gift/give-record",
    "per_page": "1",
    "prev_page_url": null,
    "to": 1,
    "total": 24
    }
    }
     */
    public function giveRecord(Request $request)
    {
        $param = $request->only('give_user_code', 'give_user_nickname', 'start_time', 'end_time', 'page', 'page_size');
        $v = app('validator')->make($param, [
            'give_user_code' => 'integer|min:1',
            'give_user_nickname' => 'string|max:16',
            'start_time' => 'date_format:Y-m-d',
            'end_time' => 'date_format:Y-m-d',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $giveUserCode = $param['give_user_code'] ?? 0;
        $giveUserNickname = $param['give_user_nickname'] ?? '';
        $startTime = $param['start_time'] ?? '';
        $endTime = $param['end_time'] ?? '';
        $pageSize = $param['page_size'] ?? 20;

        $where = [];
        if ($giveUserCode) {
            $userId = app('model_user_data')->where('user_code', $giveUserCode)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if ($giveUserNickname) {
            $userId = app('model_user_data')->where('nickname', $giveUserNickname)->value('user_id');
            $where[] = ['user_id', '=', $userId];
        }
        if ($startTime) {
            $where[] = ['created_at', '>=', $startTime . ' 0:0:0'];
        }
        if ($endTime) {
            $where[] = ['created_at', '<=', $endTime . ' 23:59:59'];
        }

        $list = app('model_v35_connection_send_record')
            ->select('id', 'user_id', 'to_user_id', 'gift_id', 'gift_op_type', 'winner_res', 'created_at')
            ->where($where)
            ->orderBy('id', 'desc')
            ->paginate($pageSize)->toArray();

        //批量查询用户code和昵称
        $userIds = array_merge(array_column($list['data'], 'user_id'), array_column($list['data'], 'to_user_id'));
        $users = app('model_user_data')
            ->select('user_id', 'user_code', 'nickname')
            ->whereIn('user_id', $userIds)
            ->get()->toArray();
        $users = array_column($users, null, 'user_id');

        //批量查询礼物名称
        $giftIds = array_column($list['data'], 'gift_id');
        $giftNames = app('model_gift')->whereIn('id', $giftIds)->pluck('name', 'id');

        foreach ($list['data'] as &$v) {
            //送礼用户code和昵称
            if (isset($users[$v['user_id']])) {
                $v['give_user_code'] = $users[$v['user_id']]['user_code'];
                $v['give_user_nickname'] = $users[$v['user_id']]['nickname'];
            } else {
                $v['give_user_code'] = '';
                $v['give_user_nickname'] = '';
            }
            //收礼用户code和昵称
            if (isset($users[$v['to_user_id']])) {
                $v['receive_user_code'] = $users[$v['to_user_id']]['user_code'];
                $v['receive_user_nickname'] = $users[$v['to_user_id']]['nickname'];
            } else {
                $v['receive_user_code'] = '';
                $v['receive_user_nickname'] = '';
            }
            //礼物名称
            if (isset($giftNames[$v['gift_id']])) {
                $v['gift_name'] = $giftNames[$v['gift_id']];
            } else $v['gift_name'] = '';
            //奖池中奖记录
            $v['winner_gift_name'] = '';
            if ($v['winner_res'] && !is_null($winnerRes = json_decode($v['winner_res'], true))) {
                foreach ($winnerRes as $v2) {
                    if (isset($v2['prop_type'])) {
                        if ($v2['prop_type'] == 1) {
                            $v['winner_gift_name'] .= app('model_gift')->where('id', $v2['prop_id'])->value('name');
                            $v['winner_gift_name'] .= '(礼物),';
                        } else {
                            $v['winner_gift_name'] .= app('model_mall_products')->where('id', $v2['prop_id'])->value('title');
                            $v['winner_gift_name'] .= '(商品),';
                        }
                    }
                }
                $v['winner_gift_name'] = rtrim($v['winner_gift_name'], ',');
            }
            unset($v['winner_res']);
        }
        return Response::sendData($list);
    }
}